package edu.sias.hyzn.controller;

import edu.sias.common.core.domain.AjaxResult;
import edu.sias.common.utils.SecurityUtils;
import edu.sias.hyzn.exception.InvalidFileFormatException;
import edu.sias.hyzn.service.impl.EyeDiagnosisService;
import edu.sias.hyzn.vo.EyeAnalysisResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hyzn/eye-analysis")
@Slf4j
public class EyeDiagnosisController {

    private final EyeDiagnosisService eyeDiagnosisService;

    @Autowired
    public EyeDiagnosisController(EyeDiagnosisService eyeDiagnosisService) {
        this.eyeDiagnosisService = eyeDiagnosisService;
    }

    @PostMapping("/upload")
    public AjaxResult uploadFiles(@RequestParam("left_eye") MultipartFile leftEyeFile, @RequestParam("right_eye") MultipartFile rightEyeFile) {
        Long doctorId = SecurityUtils.getUserId();
        String doctorName = SecurityUtils.getLoginUser().getUser().getNickName();
        try {
            EyeAnalysisResult result = eyeDiagnosisService.analysisAndSaveEyeImages(leftEyeFile, rightEyeFile, doctorId, doctorName);
            return AjaxResult.success(result);
        } catch (InvalidFileFormatException e) {
            return AjaxResult.error(400, e.getMessage());
        } catch (IOException e) {
            log.error("文件处理失败", e);
            return AjaxResult.error(500, "服务器文件处理失败");
        } catch (Exception e) {
            log.error("服务器错误", e);
            return AjaxResult.error(500, "服务器错误：" + e.getMessage());
        }
    }

    @PostMapping("/uploads")
    public AjaxResult uploadMultipleFiles(@RequestParam("left_eye") MultipartFile[] leftEyeFiles, @RequestParam("right_eye") MultipartFile[] rightEyeFiles) {
        if (leftEyeFiles.length != rightEyeFiles.length) {
            return AjaxResult.error(400, "左右眼图片数量不匹配");
        }

        Long doctorId = SecurityUtils.getUserId();
        String doctorName = SecurityUtils.getLoginUser().getUser().getNickName();

        List<CompletableFuture<EyeAnalysisResult>> futureResults = new ArrayList<>();

        for (int i = 0; i < leftEyeFiles.length; i++) {
            MultipartFile leftFile = leftEyeFiles[i];
            MultipartFile rightFile = rightEyeFiles[i];

            // 异步调用 service 方法处理每一对图片
            CompletableFuture<EyeAnalysisResult> futureResult = CompletableFuture.supplyAsync(() -> {
                try {
                    return eyeDiagnosisService.analysisAndSaveEyeImages(leftFile, rightFile, doctorId, doctorName);
                } catch (Exception e) {
                    log.error("服务器错误", e);
                    return new EyeAnalysisResult();
                }
            });
            futureResults.add(futureResult);
        }

        // 等待所有任务完成
        List<EyeAnalysisResult> results = futureResults.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        return AjaxResult.success(results);
    }
}
